package com.rxnetwork.sample.module.home.activity

import android.content.Intent
import android.content.res.AssetManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Environment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.Toast

import com.rxnetwork.bus.RxBus
import com.rxnetwork.bus.RxBusCallBack
import com.rxnetwork.sample.R
import com.rxnetwork.sample.api.Api
import com.rxnetwork.sample.api.ApiInterface
import com.rxnetwork.sample.login.LoginActivity
import com.rxnetwork.sample.model.ListModel
import com.rxnetwork.sample.module.home.adapter.MainAdapter
import com.rxnetwork.sample.module.home.fragment.TestFragment
import com.rxnetwork.sample.mvp.toolbar.BaseTopBarActivity
import com.rxnetwork.sample.utils.network.AppNetWorkListener
import com.rxnetwork.sample.utils.network.AppNetWorkManager
import okhttp3.MultipartBody

import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.util.ArrayList
import java.util.HashMap

class MainActivity : BaseTopBarActivity(), AppNetWorkListener<List<ListModel>>, SwipeRefreshLayout.OnRefreshListener {

    private var swipeRefreshLayout: SwipeRefreshLayout? = null
    private var adapter: MainAdapter? = null

    override fun initPresenter() {

    }

    override fun initViewsAndEvents() {
        topBarLayout?.leftImg?.visibility = View.GONE
        setTopBarLayoutColor(resources.getColor(R.color.colorAccent))
        topBarLayout?.rightTv?.visibility = View.VISIBLE
        topBarLayout?.rightTv?.text = "fragment"
        topBarLayout?.rightTv?.setOnClickListener {
            val testFragment = TestFragment()
            supportFragmentManager.beginTransaction().replace(R.id.test_fragment,
                    testFragment, TestFragment::class.java?.name)
                    .addToBackStack(null)
                    .commitAllowingStateLoss()
        }

        val recyclerView = findViewById(R.id.recyclerView) as RecyclerView
        swipeRefreshLayout = findViewById(R.id.activity_main) as SwipeRefreshLayout
        recyclerView.layoutManager = LinearLayoutManager(applicationContext)
        adapter = MainAdapter(this, ArrayList<ListModel>())
        adapter?.setItemClickListener(object : MainAdapter.MyItemClickListener {
            override fun onItemClick(view: View, position: Int) {
                val intent = Intent(this@MainActivity, LoginActivity::class.java)
                startActivity(intent)
            }
        })
        recyclerView.adapter = adapter
        swipeRefreshLayout?.setOnRefreshListener(this)
        swipeRefreshLayout?.post { onRefresh() }

        RxBus.instance.toSubscription("rxbusTag", object : RxBusCallBack<String> {
            override fun onNext(data: String) {
                Toast.makeText(this@MainActivity, "RxBus数据：" + data, Toast.LENGTH_SHORT).show()
            }

            override fun onError(throwable: Throwable) {
                Toast.makeText(this@MainActivity, "RxBus error：" + throwable.message, Toast.LENGTH_SHORT).show()
            }
        })

        swipeRefreshLayout?.isRefreshing = true
        AppNetWorkManager.instance.clearSubscription()
    }

    override val contentViewResId: Int
        get() = R.layout.activity_main

    override val topTitle: CharSequence
        get() = "首页"

    override fun onRefresh() {
        AppNetWorkManager
                .instance
                .setBaseUrl(Api.ZL_BASE_API)
                .getApi(AppNetWorkManager.observable(ApiInterface::class.java).getList("daily", 20, 0), this)

        val mapsTest2 = HashMap<String, String>()
        mapsTest2.put("cate", "lol")
        mapsTest2.put("pageno", "1")
        mapsTest2.put("pagenum", "20")
        test2(mapsTest2)

        //多文件上传和form表单数据
        val maps = HashMap<String, String>()
        maps.put("userName", "xiaocodeTest")
        maps.put("serviceIP", "123456")
        val listFile = ArrayList<File>()
        listFile.add(getImageFromAssetsFile("aaa.png"))
        listFile.add(getImageFromAssetsFile("bbb.png"))
        AppNetWorkManager
                .instance
                .setBaseUrl(Api.LOCAL_HOST)
                .setUploadFiles("fileKey", listFile, maps)
                .getApi(AppNetWorkManager.observable(ApiInterface::class.java).upload(AppNetWorkManager.multipartBody as MultipartBody), object : AppNetWorkListener<Any> {
                    override fun onNetWorkError(e: Throwable) {
                        Toast.makeText(applicationContext, "上传图片失败", Toast.LENGTH_SHORT).show()
                    }

                    override fun onNetWorkSuccess(data: Any) {
                        Toast.makeText(applicationContext, "上传图片成功" + data, Toast.LENGTH_SHORT).show()
                    }
                })

        val test4Map = HashMap<String, String>()
        test4Map.put("phoneNum", "15914020670")
        test4(test4Map)
    }

    fun test2(map: Map<String, String>) {
        AppNetWorkManager
                .instance
                .setBaseUrl(Api.TEST_URL)
                .getApi(AppNetWorkManager.observable(ApiInterface::class.java).getTest2String(map), object : AppNetWorkListener<Any> {
                    override fun onNetWorkError(e: Throwable) {
                        Toast.makeText(applicationContext, "请求失败-------String", Toast.LENGTH_SHORT).show()
                    }

                    override fun onNetWorkSuccess(data: Any) {
                        Toast.makeText(applicationContext, "请求成功-------String", Toast.LENGTH_SHORT).show()
                    }
                })
    }

    fun test4(map: Map<String, String>) {
        AppNetWorkManager
                .instance
                .setBaseUrl(Api.TEST2_URL)
                .getApi(AppNetWorkManager.observable(ApiInterface::class.java).getTest4String(map), object : AppNetWorkListener<Any> {
                    override fun onNetWorkError(e: Throwable) {
                        Toast.makeText(applicationContext, "请求失败4-------String", Toast.LENGTH_SHORT).show()
                    }

                    override fun onNetWorkSuccess(data: Any) {
                        Toast.makeText(applicationContext, "请求成功4-------String", Toast.LENGTH_SHORT).show()
                    }
                })
    }

    override fun onNetWorkError(e: Throwable) {
        swipeRefreshLayout?.isRefreshing = false
        Toast.makeText(applicationContext, "net work error", Toast.LENGTH_SHORT).show()
    }

    override fun onNetWorkSuccess(data: List<ListModel>) {
        swipeRefreshLayout?.isRefreshing = false
        adapter?.clear()
        adapter?.addAll(data)
    }

    /**
     * 从Assets中读取图片
     */
    private fun getImageFromAssetsFile(fileName: String): File {
        var image: Bitmap? = null
        val am = resources.assets
        try {
            val `is` = am.open(fileName)
            image = BitmapFactory.decodeStream(`is`)
            `is`.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        val file = File(Environment.getExternalStorageDirectory(), fileName)//将要保存图片的路径
        try {
            val bos = BufferedOutputStream(FileOutputStream(file))
            image?.compress(Bitmap.CompressFormat.JPEG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return file
    }

    override fun onDestroy() {
        super.onDestroy()
        //这是解绑定指定的key
        RxBus.instance.unregister("rxbusTag")
        //解除所有的key
        RxBus.instance.unregisterAll()
    }
}
